package org.misty.blog.service.impl;

import org.misty.blog.dao.TagRepository;
import org.misty.blog.exception.NotFoundException;
import org.misty.blog.po.Tag;
import org.misty.blog.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class TagServiceImpl implements TagService {
    private final TagRepository tagRepository;

    public TagServiceImpl(TagRepository tagRepository) {
        this.tagRepository = tagRepository;
    }

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public Optional<Tag> getTag(Long id) {
        return tagRepository.findById(id);
    }

    @Override
    public Optional<Tag> getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public Page<Tag> listTags(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTags() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTags(List<Long> ids) {
        return tagRepository.findAllById(ids);
    }

    @Override
    public List<Tag> listTop(int n) {
        Sort sort = Sort.by(Sort.Direction.DESC, "articles.size");
        Pageable pageable = PageRequest.of(0, n, sort);
        return tagRepository.findTop(pageable);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Optional<Tag> old = tagRepository.findById(id);
        if (!old.isPresent()) {
            throw new NotFoundException("不存在该标签 " + id);
        }
        Tag updated = old.get();
        BeanUtils.copyProperties(tag, updated);
        return tagRepository.save(updated);
    }

    @Transactional
    @Override
    public void removeTag(Long id) {
        tagRepository.deleteById(id);
    }
}
